<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;
use Illuminate\Pagination\AbstractCursorPaginator;
use Illuminate\Pagination\AbstractPaginator;

/**
 * 通用返回分页资源
 */
class BaseCollection extends ResourceCollection
{
    public function __construct($resource, string $collect)
    {
        $this->collects = $collect;
        parent::__construct($resource);
    }

    /**
     * Transform the resource collection into an array.
     *
     * @return array<int|string, mixed>
     */
    public function toArray(Request $request): array
    {
        if (($this->resource instanceof AbstractPaginator || $this->resource instanceof AbstractCursorPaginator)) {
            return [
                'data' => $this->resource->items(),
                'total' => $this->resource->total(),
                'page' => $this->resource->currentPage(),
            ];
        }

        return [
            'data' => $this->collection,
        ];
    }
}
